package com.leyou.order.interceptor;

import com.leyou.common.auth.pojo.Payload;
import com.leyou.common.auth.pojo.UserHolder;
import com.leyou.common.auth.pojo.UserInfo;
import com.leyou.common.auth.utils.JwtUtils;
import com.leyou.common.utils.CookieUtils;
import com.leyou.order.config.JwtProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 用户token验证和获取
 */
@Component
public class UserTokenInterceptor implements HandlerInterceptor{

    @Autowired
    private JwtProperties jwtProps;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        //2.验证token合法性
        Payload<UserInfo> payload = null;

        try {
            //1.从request的Cookie中取出token
            String userToken = CookieUtils.getCookieValue(request,jwtProps.getCookie().getCookieName());
            payload = JwtUtils.getInfoFromToken(userToken, jwtProps.getPublicKey(), UserInfo.class);
        } catch (Exception e) {
           return false;
        }

        //3.取出UserInfo
        UserInfo userInfo = payload.getInfo();

        //4.把UserInfo存入ThreadLo
        UserHolder.setUser(userInfo);
        return true;
    }
}
